#include "webglk.h"
#include <stdio.h>
#include <stdlib.h>

static fileref_t filerefs[20];

static frefid_t newFileRef()
{
	int i;
	for (i=1;i<20;i++)
		if (!filerefs[i].inuse)
		{
			filerefs[i].inuse=1;
			return i;
		}
	return 0;
}
frefid_t glk_fileref_create_by_prompt(glui32 usage,glui32 fmode,glui32 rock)
{
	frefid_t ref=newFileRef();
	filerefs[ref].rock=rock;
	filerefs[ref].fmode=fmode;
	if (usage!=fileusage_SavedGame)
		fatal("Trying to create a file");
	filerefs[ref].usage=usage;
	return ref;
}
frefid_t glk_fileref_create_by_name(glui32 usage,char *name,glui32 rock)
{
	// we don't need to save the name because this file ref will never
	// exist
	frefid_t ref=newFileRef();
	filerefs[ref].rock=rock;
	filerefs[ref].usage=usage;
	return ref;
}

void glk_fileref_destroy(frefid_t fref)
{
	filerefs[fref].inuse=0;
}

glui32 glk_fileref_does_file_exist(frefid_t fref)
{
	// no files exist.. we're sandboxed.
	return 0;
}

frefid_t glk_fileref_iterate(frefid_t fref,glui32 *rock)
{
	frefid_t i;
	for (i=fref+1;i<20;i++)
	{
		if (filerefs[i].inuse)
		{
			if (rock) *rock=filerefs[i].rock;
			return i;
		}
	}
	if (rock) *rock=0;
	return 0;
}


void glk_fileref_load(FILE *f)
{
	fread(filerefs,sizeof(filerefs),1,f);
}
void glk_fileref_save(FILE *f)
{
	fwrite(filerefs,sizeof(filerefs),1,f);
}
